{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ad21fc78-022a-44c1-ba22-ddaae29b3361",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "F:\\programData\\conda\\env\\ChatGLM2-6B\\lib\\site-packages\\numpy\\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:\n",
      "F:\\programData\\conda\\env\\ChatGLM2-6B\\lib\\site-packages\\numpy\\.libs\\libopenblas.FB5AE2TYXYH2IJRDKGDGQ3XBKLKTF43H.gfortran-win_amd64.dll\n",
      "F:\\programData\\conda\\env\\ChatGLM2-6B\\lib\\site-packages\\numpy\\.libs\\libopenblas64__v0.3.23-246-g3d31191b-gcc_10_3_0.dll\n",
      "  warnings.warn(\"loaded more than 1 DLL from .libs:\"\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from d2l import torch as d2l\n",
    "\n",
    "def corr2d(x,k):\n",
    "    h,w = k.shape\n",
    "    y = torch.zeros(x.shape[0] - h +1,x.shape[1] -w +1)\n",
    "    for i in range(y.shape[0]):\n",
    "        for j in range(y.shape[1]):\n",
    "            y[i,j] = (x[i:i+h,j:j+w] * k).sum()\n",
    "    return y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "451658c6-e47c-43f6-94e5-ed7c322ebab7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[19., 25.],\n",
       "        [37., 43.]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.tensor([[0.0,1.0,2.0],[3.0,4.0,5.0],[6.0,7.0,8.0]])\n",
    "y = torch.tensor([[0.0,1.0],[2.0,3.0]])\n",
    "corr2d(x,y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7579acea-0600-48f3-885c-37cc90537ce3",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Conv2D(nn.Module):\n",
    "    def __init__(self,kernel_size):\n",
    "        super().__init__()\n",
    "        self.weight = nn.Parameter(torch.rand(kernel_size))\n",
    "        self.bias = nn.Parameter(torch.zeros(1))\n",
    "    def forward(self,x):\n",
    "        return corr2d(x,self.weight) + self.bias"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f4c32abc-055e-405d-a590-14dcb9834b61",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "        [1., 1., 0., 0., 0., 0., 1., 1.]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#6.2.3. 图像中目标的边缘检测\n",
    "x = torch.ones((6,8))\n",
    "x[:,2:6] = 0\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ba4eb07a-81a7-4fea-9f6e-31ce6d05525e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "k = torch.tensor([[1.0,-1.0]])\n",
    "y = corr2d(x,k)\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "52373410-c0e6-465a-8e5c-202780ba8897",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0.]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "corr2d(x.t(),k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2190344a-0759-4407-bf36-dd4d830e282c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2,loss 9.656\n",
      "epoch 4,loss 1.914\n",
      "epoch 6,loss 0.442\n",
      "epoch 8,loss 0.124\n",
      "epoch 10,loss 0.041\n"
     ]
    }
   ],
   "source": [
    "#6.2.4. 学习卷积核\n",
    "conv2d = nn.Conv2d(1,1,kernel_size=(1,2),bias=False)\n",
    "\n",
    "x = x.reshape((1,1,6,8))\n",
    "y = y.reshape((1,1,6,7))\n",
    "lr = 3e-2\n",
    "\n",
    "for i in range(10):\n",
    "    y_hat = conv2d(x)\n",
    "    l = (y_hat - y) **2\n",
    "    conv2d.zero_grad()\n",
    "    l.sum().backward()\n",
    "\n",
    "    conv2d.weight.data[:] -= lr * conv2d.weight.grad\n",
    "    if (i+1)%2 == 0:\n",
    "        print(f\"epoch {i+1},loss {l.sum():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "93766acc-bade-43aa-9cc1-fe67f0c58d55",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 1.0040, -0.9658]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conv2d.weight.data.reshape((1,2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee617dcc-c38f-4fc6-ba2f-e6e1608887f3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
